package com.example.jobback.service.manager.impl;

import com.alibaba.fastjson.JSON;
import com.example.jobback.config.AuthConfig;
import com.example.jobback.mapper.ManagerMapper;
import com.example.jobback.po.Manager;
import com.example.jobback.po.User;
import com.example.jobback.resp.manager.common.company.MCrossComJobMessageResp;
import com.example.jobback.resp.manager.common.company.MCrossComUserMessageResp;
import com.example.jobback.resp.manager.common.manager.GetManagerMessageResp;
import com.example.jobback.resp.manager.common.company.MCrossCompanyMessageResp;
import com.example.jobback.resp.manager.common.recruiter.MCrossRecruiterMessageResp;
import com.example.jobback.resp.manager.common.seeker.MCrossSeekerMessageResp;
import com.example.jobback.resp.recruiter.company.message.RCrossComMessageResp;
import com.example.jobback.resp.recruiter.company.message.RCrossComUserMessageResp;
import com.example.jobback.resp.recruiter.profile.RecruiterCompanyResp;
import com.example.jobback.resp.seeker.common.SCrossSeekerResp;
import com.example.jobback.result.Result;
import com.example.jobback.service.common.UserCommonService;
import com.example.jobback.service.manager.ManagerCommonService;
import com.example.jobback.util.*;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.example.jobback.util.RedisConstants.MANAGER_KEY;

/**
 * @ClassName: ManagerCommonServiceImpl
 * @Description:
 * @Author: lhb
 * @Date: 2025/6/24
 */
@Service
public class ManagerCommonServiceImpl implements ManagerCommonService {

    @Value("${cross_service_baseurl}")
    private String crossServiceBaseUrl;


    private final RestTemplate restTemplate;
    
    
    private final UserCommonService userCommonService;
    
    
    private final CACHEUtil cacheUtil;

    private final AuthConfig authConfig;
    
    
    private final ManagerMapper managerMapper;

    public ManagerCommonServiceImpl(AuthConfig authConfig, RestTemplate restTemplate, ManagerMapper managerMapper, CACHEUtil cacheUtil, UserCommonService userCommonService) {
        this.authConfig = authConfig;
        this.restTemplate = restTemplate;
        this.managerMapper = managerMapper;
        this.cacheUtil = cacheUtil;
        this.userCommonService = userCommonService;
    }


    /**
     * @Description: 获取公司信息
     * @param companyId 
     * @return Result<MCrossCompanyMessageResp>
     * @Author lhb
     * @CreateTime 2025/6/24 20:45
     */
    @Override
    public Result<MCrossCompanyMessageResp> getCompanyMessage(Long companyId) {
        Manager manager= TLUtil.get(TLUtil.M);
        Long userId=manager.getUserId();
        MCrossCompanyMessageResp resp=crossGetCompanyMessage(companyId,userId);
        return Result.success(resp);
    }

    /**
     * @Description: 根据userid，获取管理员基本信息
     * @param userId
     * @return Result<GetManagerMessageResp>
     * @Author lhb
     * @CreateTime 2025/6/24 20:52
     */
    @Override
    public Result<GetManagerMessageResp> getManagerBasicMessage(Long userId) {
        //在redis查看用户
        String key=MANAGER_KEY+userId.toString();
        Map<Object,Object> userMap=cacheUtil.getHash(key);
        Manager manager=null;
        if(userMap.isEmpty()){
            manager=managerMapper.getManagerByUserId(userId);
            if(manager==null){
                throw new IllegalArgumentException("VALIDATION_ERROR：无此用户管理员端信息");
            }
            User user=userCommonService.getUserByUserId(userId);
            BeanUtils.copyProperties(user, manager);
        }
        else {
            // 从 Redis 获取用户 JSON 数据
            String userJson = (String) userMap.get("user");
            //反序列化
            manager = JSON.parseObject(userJson, Manager.class);
            if(manager ==null){
                throw new RuntimeException("缓存查询异常");
            }
        }
        String phone = null;
        try {
            phone = SecureEncryptionUtil.decrypt(manager.getPhoneAes(), authConfig.getPhoneSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        GetManagerMessageResp resp=new GetManagerMessageResp();
        Long age=0L;
        LocalDateTime birthDate=manager.getBirthDate();
        if (birthDate!=null) {
            age = (long) Period.between(LocalDate.from(birthDate), LocalDate.now()).getYears();
        }
        resp.setAge(age);
        resp.setPhone(phone);
        BeanUtils.copyProperties(manager, resp);
        return Result.success(resp);
    }

    /**
     * @Description: 获取指定招聘者基本信息
     * @param userId 
     * @return Result<MCrossRecruiterMessageResp>
     * @Author lhb
     * @CreateTime 2025/6/25 8:58
     */
    @Override
    public Result<MCrossRecruiterMessageResp> getRecruiterBasicMessage(Long userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        String url = crossServiceBaseUrl + "/recruiter/company/getRecruiterBasicMessageForAdmin";
        // 手动创建 CrossServiceInvoker 实例
        CrossServiceInvoker invoker =
                new CrossServiceInvoker(authConfig, restTemplate);
        Result<RecruiterCompanyResp> result = null;
        try {
            result = invoker.invokeAndHandle(
                    url,
                    HttpMethod.POST,
                    null,
                    RecruiterCompanyResp.class,
                    userId,
                    params
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!result.getCode().equals(HttpServletResponse.SC_CREATED)) {
            throw new IllegalArgumentException("VALIDATION_ERROR：无此用户招聘端信息");
        }
        MCrossRecruiterMessageResp resp=new MCrossRecruiterMessageResp();
        BeanUtils.copyProperties(result.getData(), resp);
        return Result.success(resp);
    }

    /**
     * @Description: 跨服务，调用方，获取指定求职者基本信息
     * @param userId 
     * @return Result<MCrossSeekerMessageResp>
     * @Author lhb
     * @CreateTime 2025/6/25 9:45
     */
    @Override
    public Result<MCrossSeekerMessageResp> getSeekerBasicMessage(Long userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        String url = crossServiceBaseUrl + "/seeker/common/getSeekerBasicMessageForAdmin";
        // 手动创建 CrossServiceInvoker 实例
        CrossServiceInvoker invoker =
                new CrossServiceInvoker(authConfig, restTemplate);
        Result<SCrossSeekerResp> result = null;
        try {
            result = invoker.invokeAndHandle(
                    url,
                    HttpMethod.POST,
                    null,
                    SCrossSeekerResp.class,
                    userId,
                    params
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!result.getCode().equals(HttpServletResponse.SC_CREATED)) {
            throw new IllegalArgumentException("VALIDATION_ERROR：无此用户招聘端信息");
        }
        MCrossSeekerMessageResp resp=new MCrossSeekerMessageResp();
        BeanUtils.copyProperties(result.getData(), resp);
        return Result.success(resp);
    }


    /**
     * @Description: 跨服务获取公司信息
     * @param companyId
     * @param userId 
     * @return MCrossCompanyMessageResp
     * @Author lhb
     * @CreateTime 2025/6/24 20:45
     */
    public MCrossCompanyMessageResp crossGetCompanyMessage(Long companyId,Long userId){
        MCrossCompanyMessageResp resp=new MCrossCompanyMessageResp();
        resp.setMCrossComJobMessageRespList(new ArrayList<>());
        resp.setMCrossComUserMessageRespList(new ArrayList<>());
        Map<String, Object> params = new HashMap<>();
        params.put("companyId", companyId);
        String url = crossServiceBaseUrl + "/recruiter/company/getCompanyMessageForAdmin";
        // 手动创建 CrossServiceInvoker 实例
        CrossServiceInvoker invoker =
                new CrossServiceInvoker(authConfig, restTemplate);
        Result<RCrossComMessageResp> result = null;
        try {
            result = invoker.invokeAndHandle(
                    url,
                    HttpMethod.POST,
                    null,
                    RCrossComMessageResp.class,
                    userId,
                    params
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        BeanUtils.copyProperties(result.getData(),resp);
        // 映射公司员工列表
        List<MCrossComUserMessageResp> userMessageList = result.getData().getRCrossComUserMessageRespList().stream()
                .map(r -> {
                    MCrossComUserMessageResp m = new MCrossComUserMessageResp();
                    BeanUtils.copyProperties(r, m); // Ensure correct order
                    return m;
                })
                .collect(Collectors.toList());

        resp.setMCrossComUserMessageRespList(userMessageList);
        // 映射公司职位列表
        List<MCrossComJobMessageResp> jobMessageList = result.getData().getRCrossComJobMessageRespList().stream()
                .map(rJob -> {
                    MCrossComJobMessageResp mJob = new MCrossComJobMessageResp();
                    //映射职位的个人用户字段
                    RCrossComUserMessageResp rUser = rJob.getRCrossComUserMessageResp();
                    MCrossComUserMessageResp mUser = new MCrossComUserMessageResp();
                    BeanUtils.copyProperties(rUser, mUser);
                    mJob.setMCrossComUserMessageResp(mUser);
                    //映射其他字段
                    BeanUtils.copyProperties(rJob, mJob);
                    return mJob;
                })
                .collect(Collectors.toList());

        resp.setMCrossComJobMessageRespList(jobMessageList);
        return resp;
    }
}
